/**
 * @api post controller.
 *
 * User: yunshengzhu
 * Date: 2020-02-16
 * Time: 21:56
 */
package control

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"pkg/cfg"
	"time"
)

var scAccessToken string
var scAccessTokenTime int64

type ScAccessModel struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int64  `json:"expires_in"`
}

type BatchgetResp struct {
	Errcode    string `json:"errcode"`
	Errmsg     string `json:"errmsg"`
	ItemCount  int64  `json:"item_count"`
	TotalCount int64  `json:"total_count"`
	Item       []Item `json:"item"`
}

type Item struct {
	MediaId string `json:"media_id"`
	Content struct {
		NewsItem   []NewsItem `json:"news_item"`
		CreateTime int64      `json:"create_time"`
		UpdateTime int64      `json:"update_time"`
	} `json:"content"`
}

type NewsItem struct {
	Title            string `json:"title"`
	Author           string `json:"author"`
	Digest           string `json:"digest"`
	Content          string `json:"content"`
	ContentSourceUrl string `json:"content_source_url"`
	ThumbMediaId     string `json:"thumb_media_id"`
	Url              string `json:"url"`
	ThumbUrl         string `json:"thumb_url"`
}

type WxSortResp struct {
	ShortUrl string `json:"short_url"`
}

func WxSortUrl(path string) string {
	accessToken, err := GetScAccessToken()
	if err != nil {
		cfg.LogErr("err:", err)
		return ""
	}
	url := fmt.Sprintf(`https://api.weixin.qq.com/cgi-bin/shorturl?access_token=%s`, accessToken)
	param := make(map[string]interface{})
	param["action"] = "long2short"
	param["long_url"] = path
	data, _ := json.Marshal(param)
	resp, err := http.Post(url, "application/xml; charset=utf-8", bytes.NewBuffer(data))
	if err != nil {
		cfg.LogErr("err:", err)
		return ""
	}
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		cfg.LogErr("err:", err)
		return ""
	}
	cfg.LogInfo("b:", string(b))
	rp := WxSortResp{}
	err = json.Unmarshal(b, &rp)
	if err != nil {
		cfg.LogErr("err:", err)
	}
	return rp.ShortUrl
}

func BatchgetMaterial(typ string, offset int64, count int64) (batchge BatchgetResp, err error) {
	accessToken, err := GetScAccessToken()
	if err != nil {
		cfg.LogErr("err:", err)
		return batchge, err
	}
	url := fmt.Sprintf(`https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=%s`, accessToken)
	param := make(map[string]interface{})
	param["type"] = typ
	param["offset"] = offset
	param["count"] = count
	data, _ := json.Marshal(param)
	resp, err := http.Post(url, "application/xml; charset=utf-8", bytes.NewBuffer(data))
	if err != nil {
		return batchge, err
	}
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		cfg.LogErr("err:", err)
		return batchge, err
	}
	err = json.Unmarshal(b, &batchge)
	if err != nil {
		cfg.LogErr("err:", err)
	}
	return batchge, nil
}

func GetScAccessToken() (string, error) {
	if scAccessTokenTime > time.Now().Unix() {
		return scAccessToken, nil
	}

	url := fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", "wx8f278cc14ab7d0fa", "75b8b86a5fc34428720ea35a8e6dca2a")
	resp, err := http.Get(url)
	//关闭资源
	if resp != nil && resp.Body != nil {
		defer resp.Body.Close()
	}
	if err != nil {
		return "", errors.New("request token err :" + err.Error())
	}
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		cfg.LogErr("err:", err)
		return "", err
	}
	cfg.LogInfo("b:", string(b))

	acc := AccessModel{}

	err = json.Unmarshal(b, &acc)
	if err != nil {
		cfg.LogErr("err:", err)
	}

	if len(acc.AccessToken) <= 0 {
		return "", errors.New("获取失败")
	}

	scAccessToken = acc.AccessToken
	scAccessTokenTime = acc.ExpiresIn + time.Now().Unix() - 120
	return scAccessToken, nil
}
